package com.tanguy.user.ui.trip.activity.work

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import cn.sinata.xldutils_kotlin.callPhone
import cn.sinata.xldutils_kotlin.utils.screenHeight
import cn.sinata.xldutils_kotlin.utils.screenWidth
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.azhong.ratingbar.RatingBar
import com.sothree.slidinguppanel.SlidingUpPanelLayout
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImageViewTang
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.bean.orde.TripOrder
import com.tanguy.user.ui.window.MessageWindow
import com.tanguy.user.utlis.RxBus
import com.tanguy.user.utlis.StackManager
import com.tanguy.user.utlis.extend.*
import org.jetbrains.anko.find

/**
 * Created by dab on 2017/12/7 0007 10:47
 * 乘车主要的页面
 * 需要  TripOrder
 */

class TripWorkActivity : ImmersionTitleActivity() {
    override fun setContentViewRes(): Int = R.layout.activity_trip_work
    override fun fullScreen(): Boolean = true
    private val tabLayout by lazy { find<TabLayout>(R.id.tab_title) }
    private val aMap by lazy { find<MapView>(R.id.map).map }
    private lateinit var tripOrder: TripOrder
    private var aMapLocationClient: AMapLocationClient? = null
    private var myLatitude = 0.0 // 我当前的位置
    private var myLongitude = 0.0
    private var myMarker: Marker?=null
    private var driverMarker: Marker?=null
    override fun initView() {
        super.initView()
        val status_bar: View = findViewById(R.id.view_status_bar)
        status_bar.visibility = View.VISIBLE
        tripOrder = intent.getParcelableExtra("TripOrder")
        loge(tripOrder)
        tabLayout.apply {
            addTab(newTab().setText("详情"))
            addTab(newTab().setText("轨迹"))
            addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    onTabItemSelected(tab.position)
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {}
                override fun onTabUnselected(tab: TabLayout.Tab?) {}
            })
        }
        find<SlidingUpPanelLayout>(R.id.sup).apply {
            isClipPanel = false
            isOverlayed = true
            panelState = SlidingUpPanelLayout.PanelState.EXPANDED
        }
        upDriver(tripOrder)
    }


    override fun initEvent() {
        super.initEvent()
        initRxBus()
        initMap()
        click(R.id.tv_back) { finish() }
        click(R.id.tv_cancel) {
            showPopupWindow(MessageWindow(this, "确认取消订单？") {
                if (it) {
                    cancelOrder(tripOrder.orderId.toString()) {
                        finish()
                    }
                }
            })
        }
        rxPermissionsLocation {
            location {
                if (it == null) return@location
                val latitude = it.latitude
                val longitude = it.longitude
                myLatitude = latitude
                myLongitude = longitude
                moveCamera(latitude, longitude, 18f)
            }
            location(5000L) { aMapLocation, aMapLocationClient ->
                this.aMapLocationClient = aMapLocationClient
                if (aMapLocation == null) return@location
                myLatitude = aMapLocation.latitude
                myLongitude = aMapLocation.longitude
                //显示自己的位置
                if (true) {
//                    upMyMarker("距您2.6公里")
                    upDriverMarker(LatLng(myLatitude, myLongitude))
                }

            }

        }

    }
    /**
     * 更新自己的位置和文字
     */
    private fun upMyMarker(message: String) {
        myMarker?.remove()
        val view = LayoutInflater.from(this).inflate(R.layout.layout_map_location, null)
        view.setText(R.id.tv_content,message)
        myMarker = aMap.addMarker(getMarkerOptions(LatLng(myLatitude, myLongitude),view ))
    }

    /**
     * 更新司机的图标
     */
    private fun upDriverMarker(latLng:LatLng) {
        driverMarker?.remove()
        val view = LayoutInflater.from(this).inflate(R.layout.layout_driver_location, null)
        driverMarker = aMap.addMarker(getMarkerOptions(latLng,view))
    }

    private fun getMarkerOptions(latLng:LatLng,view:View): MarkerOptions {
        val driverMarkerOptions = MarkerOptions()
        driverMarkerOptions.icon(BitmapDescriptorFactory.fromView(view))
        driverMarkerOptions.position(latLng)
        return driverMarkerOptions
    }

    private fun initMap() {
        val uiSettings = aMap.uiSettings
        uiSettings.isZoomControlsEnabled = false
        uiSettings.logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT//设置logo位置
        aMap.setPointToCenter(screenWidth()/2,screenHeight()*2/3)
    }

    private fun initRxBus() {
        //司机接单了
        compositeDisposable.add(RxBus.instance.register<TripOrder>(Const.RxType.ORDER_GRAB)
                .subscribe {
                    it.orderId = tripOrder.orderId
                    tripOrder = it
                    upDriver(it)
                })
        //状态改变
        compositeDisposable.add(RxBus.instance.register<TripOrder>(Const.RxType.USER_ORDER_STATE)
                .subscribe {
                    it.orderId = tripOrder.orderId
                    tripOrder = it
                    upDriver(it)
                })
    }

    /**
     * 更新状态
     */
    private fun upState(tripOrder: TripOrder) {
        setVisibility(R.id.layout_map, tripOrder.state <= 3 || tripOrder.state >= 7)

        when (tripOrder.state) {
            0, 1, 2 -> {
                //1=待支付 2=待接单
            }
            3 -> {
                //司机已接单
            }
            4 -> {
                //出发前往预约地点
                setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
            }
            5 -> {
                //到达预约地点
                setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
            }
            6 -> {
                //开始行程(开始服务了)
                setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
                find<View>(R.id.view_two).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_three, "服务中", R.color.color_333333).setDrawable(top = R.mipmap.fuwu_02)
            }
            7 -> {
                //完成未评价
                setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
                find<View>(R.id.view_two).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_three, "服务中", R.color.color_333333).setDrawable(top = R.mipmap.fuwu_02)
                find<View>(R.id.view_three).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_four, "评价司机", R.color.color_333333).setDrawable(top = R.mipmap.pingjia_02)
                setVisibility(R.id.layout_evaluate, true)
            }
            8 -> {
                //已评价
                setVisibility(R.id.layout_evaluate, true)
                 find<View>(R.id.btn_next).visibility=View.INVISIBLE
                find<EditText>(R.id.et_evaluate).isFocusable = false
                find<RatingBar>(R.id.rb_grade).isClickable = false


                setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
                find<View>(R.id.view_two).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_three, "服务中", R.color.color_333333).setDrawable(top = R.mipmap.fuwu_02)
                find<View>(R.id.view_three).setBackgroundColor(getColorKt(R.color.color_fb408e))
                setText(R.id.tv_four, "评价司机", R.color.color_333333).setDrawable(top = R.mipmap.pingjia_02)
            }
            9 -> {
                //无偿取消(飞机延误或者没司机接单的时候)
                setVisibility(R.id.layout_cancel, true)
                setText(R.id.tv_cancel_title,"无偿取消")
                setText(R.id.tv_cancel_money,"￥"+tripOrder.cenlmoney)
                setText(R.id.tv_cancel_reason,tripOrder.cenlyy)
                setText(R.id.tv_cancel_reason_concreteness,tripOrder.cenlms)
                if (tripOrder.laststate.toInt()<5) {
                    setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                    find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_two, "取消订单", R.color.color_333333).setDrawable(top = R.mipmap.quxiao_02)
                    find<View>(R.id.view_two).visibility = View.GONE
                    find<View>(R.id.tv_three).visibility = View.GONE
                    find<View>(R.id.view_three).visibility = View.GONE
                    find<View>(R.id.tv_four).visibility = View.GONE
                } else {
                    setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                    find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
                    find<View>(R.id.view_two).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_three, "取消订单", R.color.color_333333).setDrawable(top = R.mipmap.quxiao_02)
                    find<View>(R.id.view_three).visibility = View.GONE
                    find<View>(R.id.tv_four).visibility = View.GONE
                }
            }
            10 -> {
                //有偿取消(3种收费)
                setVisibility(R.id.layout_cancel, true)
                setText(R.id.tv_cancel_title,"有偿取消")
                setText(R.id.tv_cancel_money,"￥"+tripOrder.cenlmoney)
                setText(R.id.tv_cancel_reason,tripOrder.cenlyy)
                setText(R.id.tv_cancel_reason_concreteness,tripOrder.cenlms)
                if (tripOrder.laststate.toInt()<5) {
                    setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                    find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_two, "取消订单", R.color.color_333333).setDrawable(top = R.mipmap.quxiao_02)
                    find<View>(R.id.view_two).visibility = View.GONE
                    find<View>(R.id.tv_three).visibility = View.GONE
                    find<View>(R.id.view_three).visibility = View.GONE
                    find<View>(R.id.tv_four).visibility = View.GONE
                } else {
                    setText(R.id.tv_one, "等待接驾", R.color.color_333333).setDrawable(top = R.mipmap.dengdai_02)
                    find<View>(R.id.view_one).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_two, "等待上车", R.color.color_333333).setDrawable(top = R.mipmap.shangce_02)
                    find<View>(R.id.view_two).setBackgroundColor(getColorKt(R.color.color_fb408e))
                    setText(R.id.tv_three, "取消订单", R.color.color_333333).setDrawable(top = R.mipmap.quxiao_02)
                    find<View>(R.id.view_three).visibility = View.GONE
                    find<View>(R.id.tv_four).visibility = View.GONE
                }
            }
        }
    }

    /**
     * 更新司机信息
     */
    private fun upDriver(tripOrder: TripOrder) {
        if (tripOrder.state <= 2) {
            find<View>(R.id.view_driver).visibility = View.GONE
            find<View>(R.id.view_no_driver).visibility = View.VISIBLE
        } else {
            find<View>(R.id.view_driver).visibility = View.VISIBLE
            find<View>(R.id.view_no_driver).visibility = View.GONE

            find<ImageViewTang>(R.id.iv_portrait).setImageURI(tripOrder.img)
            find<RatingBar>(R.id.rb_grade).star = tripOrder.score.toInt()
            setText(R.id.tv_name_number, tripOrder.getdName() + " " + hindCarNumber(tripOrder.plate))
            setText(R.id.tv_car_type, tripOrder.brand + tripOrder.model)
            setText(R.id.tv_grade, tripOrder.score.toString())
            upState(tripOrder)
        }

        setText(R.id.tv_time, getTimeDDMM(tripOrder.departtime))
        setText(R.id.tv_car_greadname, tripOrder.greadname)
        setText(R.id.tv_start, tripOrder.departure)
        setText(R.id.tv_end, tripOrder.bourn)
        setText(R.id.tv_money, tripOrder.money.toReserveDecimal(2) + "元")
        click(R.id.tv_call_phone) { StackManager.currentActivity().callPhone(tripOrder.phone) }
    }

    /**
     * 显示轨迹
     */
    private fun getTrack() {

    }

    /**
     * 移动地图
     */
    private fun moveCamera(latitude: Double, longitude: Double, zoom: Float) {
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(latitude, longitude), zoom))
    }

    private fun onTabItemSelected(position: Int) {
        if (position == 0) {
            find<View>(R.id.sup).visibility = View.VISIBLE
            find<View>(R.id.view_track).visibility = View.GONE
        } else {
            find<View>(R.id.sup).visibility = View.GONE
            find<View>(R.id.view_track).visibility = View.VISIBLE
            getTrack()
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        find<MapView>(R.id.map).onCreate(savedInstanceState)
    }

    @SuppressLint("MissingSuperCall")
    override fun onPause() {
        super.onPause()
        find<MapView>(R.id.map).onPause()
    }

    @SuppressLint("MissingSuperCall")
    override fun onResume() {
        super.onResume()
        find<MapView>(R.id.map).onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        find<MapView>(R.id.map).onDestroy()
        aMapLocationClient?.stopLocation()
        aMapLocationClient?.onDestroy()
    }
}
